package vipcard.meichehui.service.serviceimpl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vipcard.meichehui.dao.CardMapper;
import vipcard.meichehui.dao.CardMoneyMapper;
import vipcard.meichehui.dao.VipMapper;
import vipcard.meichehui.dao.VipVoMapper;
import vipcard.meichehui.domain.*;
import vipcard.meichehui.service.Cardservice;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class CardServiceImpl implements Cardservice {

    @Autowired
    private CardMapper cardMapper;

    @Autowired
    private CardMoneyMapper cardMoneyMapper;

    @Autowired
    private VipMapper vipMapper;
    @Autowired
    private VipVoMapper vipVoMapper;


    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int RANDOM_LENGTH = 4;


    // 填写你的AccessKey ID和AccessKey Secret
    private static final String ACCESS_KEY_ID = "LTAI5tSpNyWhEB2B8f3DEi7Y";
    private static final String ACCESS_KEY_SECRET = "tf4HZTa5MksXjK9mp5QOTnpAkKdVmQ";

    @Override
    public String login(User user, HttpSession httpSession) {

        String login = cardMapper.login(user.getUsername(), user.getPassword());

        System.out.println(login);
        if (login != null) {
            System.out.println(login + "+++++++++++++++++++++");
            return login;
        }
        return null;
    }

    @Override
    public Integer vipinfo(Vip vip) {
//???????????????????????
        String findvip = vipMapper.findvip(vip.getIdname());

        String findvipbiand = vipMapper.findvipbiand(findvip);

//        String findvipbiand1 = vipMapper.findvipbiand(vip.getCarnumber());

        String findsysvip = vipMapper.findsysvip(vip.getCarnumber());

        log.info(findsysvip+"查询到的车牌号是否存在");
        if (findvipbiand!=null){
            return 2;

        }else if (findsysvip!= null){
            return 2;

        }

        if (findvip != null) {

            //修改小程序名字

            char[] chars = vip.getCarnumber().toCharArray();
            for (int i = 0, length = chars.length; i < length; i++) {
                char c = chars[i];
                //判断字母是不是大写，如果是大写变为小写
                if (Character.isUpperCase(c)){
//                    chars[i] = Character.toLowerCase(c);
                    continue;
                }
                //如果为小写，变为大写
                chars[i] = Character.toUpperCase(c);
            }

            String carnumber = new String(chars);

            Integer updata = vipMapper.updata(vip.getIdname(), carnumber);

            System.out.println(updata);
            return 1;
        }

        return null;
    }

    @Override
    public Integer addcard(Vip vip, HttpSession session) {

        User biand = cardMapper.biand(vip.getCarnumber());
        if (biand != null && !Objects.equals(biand.getUsername(), session.getAttribute("username").toString())) {

//            System.out.println(session.getAttribute("username")+"--------------------"+biand.getUsername()+"+++++++++++++++++++++++++++++++++++++++++++++++++++++");

            log.info("无法添加........." + "登录用户为:  " + session.getAttribute("username") + "   绑定用户为:" + biand.getUsername());
            if (biand.getType().equals("1")) {
                return 3;

            }
            return 3;
        }

        System.out.println(vip.getCarnumber());
        if (cardMapper.biand(vip.getCarnumber()) != null) {
            System.out.println("直接添加");
            return addcardexize(vip);
        } else {
            System.out.println("直接添加");

            Integer username = cardMapper.adduser(vip.getPhonenumber(), vip.getCarnumber(), session.getAttribute("username").toString(), "", 0, "1");
            return addcardexize(vip);
        }


    }

    private Integer addcardexize(Vip vip) {
        String temp = "1";
        StringBuilder couponCode = new StringBuilder();

        // 获取当前时间戳，并格式化为字符串
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMdd");
        String timestamp = dateFormat.format(new Date());

        // 将时间戳添加到couponCode
        couponCode.append(timestamp);

        // 生成剩余长度的随机数字
        Random random = new Random();
        for (int i = 0; i < RANDOM_LENGTH; i++) {
            couponCode.append(random.nextInt(10));  // 生成一个0到9之间的随机数
        }

        // 转换为整数类型，并确保不会超过int的最大范围
        int couponNumber = Integer.parseInt(couponCode.toString());
        if (couponNumber > Integer.MAX_VALUE) {
            throw new RuntimeException("Generated coupon number exceeds int max value");
        }

        String cardname = "";
        switch (vip.getRadio()) {
            case "1":
                // 处理case 1的代码
                cardname = "轿车普洗次卡300元12次";
                break;
            case "2":
                // 处理case 2的代码
                cardname = "越野车普洗次卡 500 12次";
                break;
            case "3":
                // 处理case 3的代码
                cardname = "贴膜优惠券 100元";
                break;
            case "4":
                // 处理case 4的代码
                cardname = "夏日畅洗卡188元10次";
                break;
            case "5":
                // 处理case 5的代码
                cardname = "雨季补偿卡";
                break;
            case "6":
                // 处理case 6的代码
                cardname = "通用补偿卡";
                break;
            case "7":
                // 处理case 7的代码
                cardname = "打蜡卷";
                break;
            case "8":
                // 处理case 8的代码
                cardname = "精洗卷";
                break;
            case "9":
                // 处理case 9的代码
                cardname = "微精洗卷";
                break;
            case "10":
                // 处理case 10的代码
                cardname = "保养卷";
                break;
            case "11":
                // 处理case 11的代码
                cardname = "200元储值";
                vip.setPhonenumber("200元");
                break;
            case "12":
                // 处理case 12的代码
                cardname = "300元储值";
                vip.setPhonenumber("300元");
                break;
            case "13":
                // 处理case 13的代码
                cardname = "400元储值";
                vip.setPhonenumber("400元");
                break;
            default:
                // 处理所有其他情况的代码

                break;
        }

        System.out.println(cardname);
        //查询该用户下是否有多张卡卷

        List<CardRemarks> selectbyone = vipVoMapper.selectbyone(vip.getIdname());

        log.info(String.valueOf(selectbyone.size()));
        if (selectbyone.size() > 1) {

            log.info("该用户有多张卡卷禁止添加");
            return 3;

//          if (vip.getRadio().equals("11")||vip.getRadio().equals("12")||vip.getRadio().equals("13")){
//              return
//
//          }
        }


        Integer addcard = vipVoMapper.addcard(Integer.parseInt(couponCode.toString()), cardname, vip.getIdname(), temp, vip.getPhonenumber());


        if (addcard != 0) {
            log.info("添加成功");


            return addcard;

        }

        log.info("非正常添加");
        return 2;
    }

    @Override
    public List<VipVo> findall(HttpSession session) {

        List<User> findalluser = cardMapper.findall(session.getAttribute("username").toString());

        ArrayList<VipVo> vipVos = new ArrayList<>();

        for (int i = 0; i < findalluser.size(); i++) {
            VipVo vipVo = new VipVo();
            System.out.println(findalluser.get(i));
            vipVo.setDescription(findalluser.get(i).getId());
            vipVo.setTitle(findalluser.get(i).getCarnumber());

            if (findalluser.get(i).getCarnumber() != null) {
                vipVos.add(vipVo);
            }


        }


        return vipVos;
    }

    @Override
    public List<VipVo> getHistoryRecords(String identifier) {
        return null;
    }

    @Override
    public Integer deductFee(CarMoney carMoney, String session) {


//        Vip findbyid = cardMoneyMapper.findbyid(carMoney.getHexiaophone());
//        if (findbyid!=null){
//
//            return null;
//        }

        //查询该用户绑定跟当前用户是否一致

        User biand = cardMapper.biand(carMoney.getHexiaophone());


        if (carMoney.getHexiaophone().equalsIgnoreCase(session)) {
            log.info(biand.getUsername() + "++++++++" + session);
            log.info("不扣");
            return 6;
        } else {

            log.info("扣费");
//            return 1;

        }

        char[] chars = carMoney.getHexiaophone().toCharArray();
        for (int i = 0, length = chars.length; i < length; i++) {
            char c = chars[i];
            //判断字母是不是大写，如果是大写变为小写
            if (Character.isUpperCase(c)){
//                chars[i] = Character.toLowerCase(c);
                continue;
            }
            //如果为小写，变为大写
            chars[i] = Character.toUpperCase(c);
        }
        String carnumber = new String(chars);


        log.info(carnumber);


        Integer findbyid = cardMoneyMapper.findbyid(carnumber);//UID



        String money = cardMoneyMapper.findMoney(findbyid.toString());//原始金额

        Integer moneya = 0;

        String[] s = money.split("元");

        Integer moneyb = 0;
        switch (carMoney.getKoufeiradio()) {
            case "1":
                moneya = 25;
                Integer m = Integer.valueOf(s[0]);
                moneyb = m - moneya;
                break;

            case "2":
                moneya = 35;
                Integer m1 = Integer.valueOf(s[0]);
                moneyb = m1 - moneya;
                break;
            case "3":
                moneya = 45;
                Integer m2 = Integer.valueOf(s[0]);
                moneyb = m2 - moneya;
                break;


        }

        if (moneyb < 0) {
            return 3;
        }
        Integer heixiao = cardMoneyMapper.heixiao(moneyb + "元", String.valueOf(findbyid));

        System.out.println(carMoney + "+++++++++++++++++++++");
        log.info(carMoney.getHexiaophone());


        String phone = vipVoMapper.selectCarnum(carMoney.getHexiaophone());

        log.info(phone);
        if (heixiao == 1) {
//发送短信放发

            // 设置超时时间-可自行调整
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");

            // 初始化ascClient需要的几个参数
            final String product = "Dysmsapi"; // 短信API产品名称（短信产品名固定，无需修改）
            final String domain = "dysmsapi.aliyuncs.com"; // 短信API产品域名（接口地址固定，无需修改）

            // 初始化ascClient,暂时不支持多region（请勿修改）
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            try {
                DefaultProfile.addEndpoint("cn-hangzhou", product, domain);
            } catch (Exception e) {
                e.printStackTrace();
//                return;
            }
            IAcsClient acsClient = new DefaultAcsClient(profile);

            // 组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            // 必填: 待发送手机号
            request.setPhoneNumbers(phone);
            // 必填: 短信签名-可在短信控制台中找到
            request.setSignName("美车汇");
            // 必填: 短信模板-可在短信控制台中找到
            request.setTemplateCode("SMS_468260320");
            // 可选: 模板中的变量替换JSON串, 如模板内容为"验证码为${code}"时, 此处的值为

            Map<String, String> templateParam = new HashMap<>();
            templateParam.put("num1", String.valueOf(moneya));
            templateParam.put("num2", String.valueOf(moneyb));

            // 将模板参数Map转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String jsonTemplateParam = objectMapper.writeValueAsString(templateParam);
                request.setTemplateParam(jsonTemplateParam);
            } catch (Exception e) {
                e.printStackTrace();
//                return;
            }
//            request.setTemplateParam("{\"num1\":\"50.00\", \"num2\":\"100.00\"}");

            // hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse;
            try {
                sendSmsResponse = acsClient.getAcsResponse(request);
                if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                    // 请求成功
                    System.out.println("短信发送成功！");
                } else {
                    // 请求失败
                    System.out.println("短信发送失败！错误码：" + sendSmsResponse.getCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 1;
        }
        return null;
    }

    @Override
    public CardAdd selectbyid(String phone) {

        System.out.println(phone);

        Integer selectid = cardMapper.selectid(phone);


        CardAdd selectbyphonea = cardMapper.selectbyphonea(String.valueOf(selectid));


        System.out.println(selectbyphonea);

        return selectbyphonea;
    }
}
